<!--  -->
<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开始拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button @click="batchSave" v-if="draggable">批量保存</el-button>
    <el-button type="danger"  @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标地址">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submiitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      draggable: false,
      pCid: [],
      updateNodes: [],
      title: "",
      categoryType: "",
      dialogFormVisible: false,
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: "",
        catId: null,
      },
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      maxLevel: 0,
    };
  },
  created() {
    this.getMenus();
  },
  methods: {
    batchDelete() {
      let chekedNodes = this.$refs.menuTree.getCheckedNodes();
      let catIds = [];
      let catNames = [];
      console.log(chekedNodes)
      for (let i = 0; i < chekedNodes.length; i++) {
        catIds.push(chekedNodes[i].catId);
        catNames.push(chekedNodes[i].name);
      }
      this.$confirm(`确定对将【${catNames}】进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "菜单删除成功",
                type: "success",
              });
              this.getMenus();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    batchSave() {
      //4，保存
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "分类顺序修改成功",
          type: "success",
        });
        this.getMenus();
        //默认展开
        this.expandedKey = this.pCid;
        //数据赋零值
        this.updateNodes = [];
        this.maxLevel = 0;
        // this.pCid = 0;
      });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", draggingNode, dropNode, dropType);
      //1.当前节点的父节点id（dropNode）
      let pCid = 0;
      let sublings = null;
      if (dropType == "before" || dropType == "after") {
        let tempCid = dropNode.parent.data.catId;
        pCid = tempCid == undefined ? 0 : tempCid;
        sublings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        sublings = dropNode.childNodes;
      }
      this.pCid.push(pCid);
      // console.log(pCid, sublings);
      //遍历需要调整的nodes
      if (sublings != null && sublings.length > 0) {
        for (let i = 0; i < sublings.length; i++) {
          //判断是否为本身节点
          if (sublings[i].data.catId == draggingNode.data.catId) {
            //拖拽的节点需要考虑子节点的顺序，层级
            if (sublings[i].level == draggingNode.level) {
              //如果层级没有变化，其只是顺序移动了
              this.updateNodes.push({
                catId: sublings[i].data.catId,
                sort: i,
                parentCid: pCid,
              });
            } else {
              //考虑层级
              this.updateNodes.push({
                catId: sublings[i].data.catId,
                sort: i,
                parentCid: pCid,
                catLevel: sublings[i].level,
              });
              this.updateChildNodeLevel(sublings[i]);
            }
          } else {
            //非拖拽节点，只需要更新sort值即可
            this.updateNodes.push({ catId: sublings[i].data.catId, sort: i });
          }
        }
      }
      //2.当前节点的顺序（dropNode）
      //3.当前节点的层级（dropNode）
      console.log(this.updateNodes);
    },
    updateChildNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({
            catId: node.childNodes[i].data.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      // console.log("拖拽", draggingNode, dropNode, type);
      this.countCatLevel(draggingNode);
      // console.log("长度", this.maxLevel);
      let deep = Math.abs(this.maxLevel - draggingNode.level + 1);
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }

      // draggingNode.parent.lev
    },
    countCatLevel(node) {
      if (node != null && node.childNodes && node.childNodes.length > 0) {
        for (var i = 0; i < node.childNodes.length; i++) {
          if (this.maxLevel < node.childNodes[i].level) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countCatLevel(node.childNodes[i]);
        }
      }
    },
    allowDrag(draggingNode) {
      // console.log("拖拽",draggingNode)
      return true;
    },
    submiitData() {
      if (this.categoryType == "add") {
        this.addCategory();
      }
      if (this.categoryType == "edit") {
        this.editCategory();
      }
    },
    edit(data) {
      console.log("需要修改的", data);
      this.title = "修改分类信息";
      this.categoryType = "edit";
      this.dialogFormVisible = true;
      //从数据库获取最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        this.category.name = data.data.name;
        this.category.parentCid = data.data.parentCid;
        //   this.category.catLevel = data.data.catLevel
        //   this.category.sort = data.data.sort
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.catId = data.data.catId;
      });
    },
    editCategory() {
      // console.log("编辑数据", this.category);
      var { catId, name, icon, productUnit } = this.category;
      this.dialogFormVisible = false;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
            this.getMenus();
            this.expandedKey = [this.category.parentCid];
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch(() => {});
    },
    addCategory() {
      // console.log("提交数据", this.category);
      this.dialogFormVisible = false;
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
            this.getMenus();
            this.expandedKey = [this.category.parentCid];
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch(() => {});
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
    append(data) {
      // console.log(data);
      this.title = "新增分类信息";
      this.categoryType = "add";
      this.dialogFormVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;

      //将其他字段初始化为默认值
      this.category.catId = null;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
    },
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm(`确定对[将${data.name}]进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.getMenus();
              this.expandedKey = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang='scss' scoped>
</style>